
package com.nd.rj.common.util.db;

import java.io.File;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.nd.rj.common.R;

/**
 * @ClassName: BaseDBHelper
 * @Description: sqlite数据库操作类
 * @author Administrator
 * @date 2012-2-1 下午01:55:29
 */
public abstract class BaseDBHelper implements IDataBaseRef {
    protected String TAG = "BaseDBHelper";

    protected SqliteHelper mSqliteHelper = null;

    protected SQLiteDatabase mSQLiteDatabase = null;

    protected String mDBName = null;

    protected void createDataBasePath(File dbfile) {
        // 判断数据库目录是否存在
        File pfile = dbfile.getParentFile();
        if (!pfile.exists())
            pfile.mkdir();
    }

    @Override
    public int InsertTable(String table, ContentValues values) {
        long ireturn = mSQLiteDatabase.insert(table, null, values);
        if (ireturn != -1)
            return (int) ireturn;
        else
            return R.string.nd_exec_sql_error;
    }

    @Override
    public int UpdateTable(String table, ContentValues values, String whereClause,
            String[] whereArgs) {
        int ireturn = R.string.nd_exec_sql_error;
        try {
            mSQLiteDatabase.update(table, values, whereClause, whereArgs);
            ireturn = 0;
        } catch (Exception e) {
            Log.v(TAG, e.getMessage());
            e.printStackTrace();
        }
        return ireturn;
    }

    @Override
    public void beginTransaction() {
        if (!mSQLiteDatabase.inTransaction()) {
            mSQLiteDatabase.beginTransaction();
        }
    }

    @Override
    public void close() {
        if (mSqliteHelper != null) {
            mSqliteHelper.close();
        }
        mDBName = null;
        mSQLiteDatabase = null;
    }

    @Override
    public void endTransaction(int ireturn) {
        if (mSQLiteDatabase.inTransaction()) {
            if (ireturn == 0) {
                mSQLiteDatabase.setTransactionSuccessful();
            }
            mSQLiteDatabase.endTransaction();
        }
    }

    @Override
    public int execSql(String strSql) {
        int ireturn = 0;
        try {
            mSQLiteDatabase.execSQL(strSql);
        } catch (SQLException e) {
            Log.v(TAG, e.getMessage() + " sqlcmd=" + strSql);
            ireturn = R.string.nd_exec_sql_error;
        }
        return ireturn;
    }

    @Override
    public int execSql(String strSql, Object[] bindArgs) {
        int ireturn = 0;
        try {
            mSQLiteDatabase.execSQL(strSql, bindArgs);
        } catch (SQLException e) {
            Log.v(TAG, e.getMessage() + " sqlcmd=" + strSql);
            ireturn = R.string.nd_exec_sql_error;
        }
        return ireturn;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

    @Override
    public int open(Context context, String username) {
        return openDB(context, username);
    }

    @Override
    public Cursor querySql(String strSql) {
        return querySql(strSql, null);
    }

    @Override
    public Cursor querySql(String strSql, String[] selectionArgs) {
        Cursor cur = null;
        try {
            cur = mSQLiteDatabase.rawQuery(strSql, selectionArgs);
        } catch (Exception e) {
            Log.v(TAG, e.getMessage() + " sqlcmd=" + strSql);
        }
        return cur;
    }

    @Override
    public boolean tableExists(SQLiteDatabase db, String strTbl) {
        String sqlcmd = "select count(*) as number from sqlite_master where type='table' and name=?";
        Cursor cur = db.rawQuery(sqlcmd, new String[] {
                strTbl
        });
        try {
            if (cur != null && cur.getCount() > 0) {
                cur.moveToFirst();
                return cur.getInt(0) > 0;
            }
        } finally {
            closeCursor(cur);
        }
        return false;
    }

    @Override
    public boolean columnExists(SQLiteDatabase db, String strTbl, String strCol) {
        String sqlcmd = "select * from " + strTbl + " where 1=2";
        Cursor cur = db.rawQuery(sqlcmd, null);
        try {
            if (cur != null) {
                return cur.getColumnIndex(strCol) >= 0;
            }
        } finally {
            closeCursor(cur);
        }
        return false;
    }

    /**
     * @Title: openDB
     * @Description: 打开数据库
     * @author Administrator
     * @date 2012-2-1 下午01:55:33
     * @param context
     * @param username
     * @return
     * @return int
     * @throws
     */
    protected abstract int openDB(Context context, String username);

    public static void closeCursor(Cursor cur) {
        if (cur != null) {
            cur.close();
        }
    }

    /**
     * 转义单引号-写sqlite使用
     * 
     * @param str
     * @return
     */
    public static String quotedString(String str) {
        if (str.indexOf("'") >= 0)
            str = str.replaceAll("'", "''");
        return str;
    }

}
